import 'package:flutter/material.dart';
import 'package:flutter_wan_android/entity/structure_category_entity.dart';
import 'package:flutter_wan_android/entity/structure_nav_entity.dart';
import 'package:flutter_wan_android/manager/router_manger.dart';
import 'package:flutter_wan_android/provider/provider_widget_consumer.dart';
import 'package:flutter_wan_android/provider/view_state_widget.dart';
import 'package:flutter_wan_android/view_model/structure_model.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

///
/// 体系主页面
///
class StructurePage extends StatefulWidget {
  @override
  _StructurePageState createState() => _StructurePageState();
}

class _StructurePageState extends State<StructurePage> with AutomaticKeepAliveClientMixin {
  List<String> tabs = ['体系', '导航'];

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return DefaultTabController(
      length: tabs.length,
      child: Scaffold(
          appBar: AppBar(
              centerTitle: true,
              title: TabBar(
                isScrollable: true,
                tabs: List.generate(
                    tabs.length,
                    (index) => Tab(
                          text: tabs[index],
                        )),
              )),
          body: TabBarView(children: [StructureCategoryList(), NavigationSiteCategoryList()])),
    );
  }
}

/// 体系->体系
class StructureCategoryList extends StatefulWidget {
  @override
  _StructureCategoryListState createState() => _StructureCategoryListState();
}

class _StructureCategoryListState extends State<StructureCategoryList> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ProviderWidgetConsumer<StructureCategoryModel>(
        model: StructureCategoryModel(),
        onModelReady: (model) {
          model.initData();
        },
        builder: (context, model, child) {
          if (model.isBusy) {
            return ViewStateBusyWidget();
          } else if (model.isError) {
            return ViewStateErrorWidget(error: model.viewStateError, onPressed: model.initData);
          } else if (model.dataList.isEmpty) {
            return ViewStateEmptyWidget(onPressed: model.initData);
          }
          return Scrollbar(
            child: ListView.builder(
                padding: EdgeInsets.all(15),
                itemCount: model.dataList.length,
                itemBuilder: (context, index) {
                  StructureCategoryEntity item = model.dataList[index];
                  return StructureCategoryWidget(item);
                }),
          );
        });
  }
}

///
/// 体系项
///
class StructureCategoryWidget extends StatelessWidget {
  final StructureCategoryEntity categoryEntity;

  StructureCategoryWidget(this.categoryEntity);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          ///体系名称
          Text(
            categoryEntity.name,
            style: Theme.of(context).textTheme.subtitle2,
          ),

          ///体系小项
          Wrap(
              spacing: 10,
              children: List.generate(
                  categoryEntity.children.length,
                  (index) => ActionChip(
                        onPressed: () {
                          //Navigator.of(context).pushNamed(RouteName.structureList, arguments: [tree, index]);
                        },
                        label: Text(
                          categoryEntity.children[index].name,
                          maxLines: 1,
                        ),
                      )))
        ],
      ),
    );
  }
}

/// 体系->导航
class NavigationSiteCategoryList extends StatefulWidget {
  @override
  _NavigationSiteCategoryListState createState() => _NavigationSiteCategoryListState();
}

class _NavigationSiteCategoryListState extends State<NavigationSiteCategoryList> with AutomaticKeepAliveClientMixin {
  final double _menuWidth = 100;
  AutoScrollController _autoScrollController;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _autoScrollController = AutoScrollController(axis: Axis.vertical);
  }

  ///跳转到指定位置
  Future _scrollToIndex(int index) async {
    await _autoScrollController.scrollToIndex(
      index,
      preferPosition: AutoScrollPosition.begin,
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ProviderWidgetConsumer<StructureNavModel>(
        model: StructureNavModel(),
        onModelReady: (model) {
          model.initData();
        },
        builder: (context, model, child) {
          if (model.isBusy) {
            return ViewStateBusyWidget();
          } else if (model.isError) {
            return ViewStateErrorWidget(error: model.viewStateError, onPressed: model.initData);
          } else if (model.dataList.isEmpty) {
            return ViewStateEmptyWidget(onPressed: model.initData);
          }
          return Stack(
            children: [
              Positioned(
                left: 0,
                right: MediaQuery.of(context).size.width - _menuWidth,
                top: 0,
                bottom: 0,
                child: ListView.builder(
                    itemCount: model.dataList.length,
                    itemBuilder: (context, index) {
                      return RaisedButton(
                          child: Text(model.dataList[index].name),
                          onPressed: () {
                            _scrollToIndex(index);
                          });
                    }),
              ),
              Positioned(
                  left: _menuWidth,
                  right: 0,
                  top: 0,
                  bottom: 0,
                  child: Scrollbar(
                    child: ListView.builder(
                        controller: _autoScrollController,
                        padding: EdgeInsets.all(15),
                        itemCount: model.dataList.length,
                        itemBuilder: (context, index) {
                          StructureNavEntity item = model.dataList[index];
                          return AutoScrollTag(
                              key: ValueKey(index),
                              controller: _autoScrollController,
                              index: index,
                              child: NavigationSiteCategoryWidget(item));
                        }),
                  ))
            ],
          );
        });
  }
}

/// 导航项
class NavigationSiteCategoryWidget extends StatelessWidget {
  final StructureNavEntity navEntity;

  NavigationSiteCategoryWidget(this.navEntity);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            navEntity.name,
            style: Theme.of(context).textTheme.subtitle,
          ),
          Wrap(
              spacing: 10,
              children: List.generate(
                  navEntity.articles.length,
                  (index) => ActionChip(
                        onPressed: () {
                          RoutesManager.getInstance().pushArticleDetailPage(context, navEntity.articles[index]);
                        },
                        label: Text(
                          navEntity.articles[index].title,
                          maxLines: 1,
                        ),
                      )))
        ],
      ),
    );
  }
}
